package com.zone.core.coroutine

import kotlinx.coroutines.*

/**
 * Author: last
 * Time: 2021-05-01
 * Description: xxx
 */

typealias ErrorHandle = (Throwable) -> Boolean
typealias CoroutineLambda = suspend CoroutineScope.() -> Unit

@OptIn(DelicateCoroutinesApi::class)
private fun request(type: CoroutineDispatcher, block: CoroutineLambda) {
    val exceptionHandle = CoroutineExceptionHandler { _, throwable ->
        throwable.printStackTrace()
    }
    GlobalScope.launch(exceptionHandle) {
        withContext(type) {
            block()
        }
    }
}

fun request(type: CoroutineDispatcher,
    exceptionHandler: ExceptionHandler = ExceptionHandler(),
    error: ErrorHandle? = null,
    block: CoroutineLambda
) {
    request(type) {
        try {
            block()
        } catch (e: Exception) {
            e.printStackTrace()
            if (error?.invoke(e) != true) {
                exceptionHandler.handleException(e)
            }
        }
    }
}
